//
//  RecommondDetialViewController.m
//  TravelToHelp
//
//  Created by lanou3g on 15/10/29.
//  Copyright © 2015年 冯贵宾. All rights reserved.
//

#import "RecommondDetialViewController.h"
#import "ReDetialTableViewCell.h"
#import "FLSFirstHotDetialModel.h"

@interface RecommondDetialViewController ()<UITableViewDataSource, UITableViewDelegate>
// 详情列表
@property (nonatomic, strong) UITableView *detailTableView;
// 接收数据
@property (nonatomic, strong) NSMutableArray *dataArray;

@property (nonatomic, strong) UIImageView *topImage;

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, strong) DDIndicator *indicator;

@property (nonatomic, strong) UIView *viewV;



@property (nonatomic, strong) AppDelegate *app;

@end

@implementation RecommondDetialViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:@"reloadData" object:nil];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    _app = [[AppDelegate alloc] init];
    // Do any additional setup after loading the view.
    [self.navigationController.navigationBar setTranslucent:NO];
   
    [self addSubViews];
    [self setUpData];
    [self setNaviBar];
    [self addInternetObserver];
}

// 通知网络状态
- (void)addInternetObserver
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadDataWithInternet:) name:@"reloadData" object:nil];
}

- (void)reloadDataWithInternet:(NSNotification *)notification
{
    [self setUpData];
}

// 解析数据
- (void)setUpData
{
    if ([_app internetReachableOrNot]) {
    [self addAnimation];
    // 详情页面网址拼接
    NSString *url = [NSString stringWithFormat:@"http://app.xialv.com/index2.php?a=bangdandetail&id=%@&uid=0&time=1445991799&sign=fdcbd3bd1e09cf28bea47e3686c98315", self.headModel.ID];
    // 创建子线程,请求数据
    __block RecommondDetialViewController *mySelf = self;
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
    // 利用网址字符串创建一个网址对象
    NSURL *url1 = [NSURL URLWithString:url];
    // 利用网址对象创建一个请求
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url1 cachePolicy:(NSURLRequestUseProtocolCachePolicy) timeoutInterval:30.0];
    [request setHTTPMethod:@"GET"];
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *connectionError) {
        if (connectionError) {
            return ;
        }
        NSMutableDictionary *datDic =  [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
       
        NSArray *allArray = datDic[@"result"];
        mySelf.dataArray = [NSMutableArray array];
        for (NSDictionary *dic in allArray) {
            FLSFirstHotDetialModel *model = [[FLSFirstHotDetialModel alloc]init];
            [model setValuesForKeysWithDictionary:dic];
            [mySelf.dataArray addObject:model];
        }
        // 回到主线程,方便刷新数据
        dispatch_async(dispatch_get_main_queue(), ^{
            [mySelf.detailTableView reloadData];
            [self stopLoading];
        });
        
      }];
    });
    } else {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"🙅 您的当前网络中断或网络信号差, 请检查网络后重新进入!!" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
        [alert show];
    }
}

// 加载动画
- (void)addAnimation
{
    _viewV = [[UIView alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 100, kScreenHeight / 2 - 80, 200, 80)];
    _viewV.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0];
    _viewV.layer.cornerRadius = 10;
    _viewV.layer.masksToBounds = YES;
    [self.view addSubview:_viewV];
    self.indicator = [[DDIndicator alloc] initWithFrame:CGRectMake(_viewV.width / 2 - 20, _viewV.height / 2 - 20 , 40, 40)];
    [_viewV addSubview:self.indicator];
    [self.indicator startAnimating];
   // [self performSelector:@selector(stopLoading:) withObject:self.indicator afterDelay:5];
    
}

- (void)stopLoading
{
    [_indicator stopAnimating];
    [self.viewV removeFromSuperview];
}

- (void)setNaviBar
{
    self.navigationItem.title = @"火热列表";
    UIBarButtonItem *leftButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backNew.png"] style:(UIBarButtonItemStylePlain) target:self action:@selector(actionLeftButton:)];
    
    self.navigationItem.leftBarButtonItem = leftButton;
}

- (void)actionLeftButton:(UIBarButtonItem *)leftButton
{
    [self.navigationController popViewControllerAnimated:YES];
}


// 添加视图
- (void)addSubViews
{
    // tableView
    self.detailTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight - 64) style:(UITableViewStylePlain)];
    self.detailTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    // 代理
    self.detailTableView.dataSource = self;
    self.detailTableView.delegate = self;
    [self creatHeaderViewWith:self.detailTableView];
    [self.view addSubview:self.detailTableView];
    
   }

// 添加大表头
- (void)creatHeaderViewWith:(UITableView *)tableView
{
    self.headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 400)];
    self.headerView.backgroundColor = [UIColor whiteColor];
    self.topImage = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 160)];

    
    [self.topImage sd_setImageWithURL:[NSURL URLWithString:self.headModel.cover] placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
    [self.headerView addSubview:self.topImage];
    
    UIImageView *headImage = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 40, self.topImage.bottom - 40, 80, 80)];
   // headImage
    headImage.layer.cornerRadius = 40;
    headImage.layer.masksToBounds = YES;
    headImage.layer.borderColor = [UIColor whiteColor].CGColor;
    headImage.layer.borderWidth = 5;
    [headImage sd_setImageWithURL:[NSURL URLWithString:self.headModel.face_file] placeholderImage:[UIImage imageNamed:@"head_img.png"]];
    [self.headerView addSubview:headImage];
    
    UILabel *nameLB = [[UILabel alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 50, headImage.bottom, 100, 20)];
    nameLB.textColor = [UIColor grayColor];
    nameLB.text = [NSString stringWithFormat:@"by: %@", self.headModel.nickname];
    nameLB.textAlignment = YES;
    nameLB.font = [UIFont systemFontOfSize:12];
    [self.headerView addSubview:nameLB];
    
    UILabel *titleLB = [[UILabel alloc] initWithFrame:CGRectMake(0, nameLB.bottom + 5, kScreenWidth, 30)];
    titleLB.textColor = [UIColor blackColor];
    titleLB.text = [NSString stringWithFormat:@"%@", self.headModel.title];
    titleLB.textAlignment = YES;
    titleLB.font = [UIFont systemFontOfSize:20];
    [self.headerView addSubview:titleLB];
    
    UILabel *countLB = [[UILabel alloc] initWithFrame:CGRectMake(0, titleLB.bottom + 5, kScreenWidth, 20)];
    countLB.textColor = [UIColor grayColor];
    countLB.text = [NSString stringWithFormat:@"%@ 浏览数(%@)", self.headModel.ts_create, self.headModel.view_num];
    countLB.textAlignment = YES;
    countLB.font = [UIFont systemFontOfSize:12];
    [self.headerView addSubview:countLB];
    
    UIImageView *frontImage = [[UIImageView alloc] initWithFrame:CGRectMake(10, countLB.bottom, 20, 20)];
    frontImage.image = [UIImage imageNamed:@"iconfont-qianyinhao"];
    [self.headerView addSubview:frontImage];
    
    UILabel *descripLB = [[UILabel alloc] initWithFrame:CGRectMake(10, frontImage.bottom - 5, kScreenWidth - 20, 90)];
    descripLB.text = [NSString stringWithFormat:@"%@", self.headModel.content];
    descripLB.textAlignment = YES;
    descripLB.textColor = [UIColor colorWithWhite:0.400 alpha:1.000];
    descripLB.font = [UIFont systemFontOfSize:14];
    descripLB.numberOfLines = 0;
    [self.headerView addSubview:descripLB];
    
    UIImageView *lateImage = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth - 30, descripLB.bottom - 5, 20, 20)];
    lateImage.image = [UIImage imageNamed:@"iconfont-houyinhao"];
    [self.headerView addSubview:lateImage];
    
    tableView.tableHeaderView = self.headerView;
}



#pragma mark -- UITableViewDataSource协议
// 行数
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{

    return self.dataArray.count;
}

// cell样式
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *identifier = @"detialCell";
    ReDetialTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[ReDetialTableViewCell alloc] initWithStyle:(UITableViewCellStyleSubtitle) reuseIdentifier:identifier];
    }
    if (self.dataArray > 0) {
        cell.userInteractionEnabled = NO;
        cell.model = self.dataArray[indexPath.row];
    }
    return cell;
}




// 行高
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 530;
}

@end
